var lumb;
var jsonp;
var eve;
var instance;
//连接线的样式
var common = {
    isSource: true,
    isTarget: true,
    endpoint: 'Dot',
    endpointStyle: {fill: '#7AB02C', outlineStroke: 'darkgray', outlineWidth: 2, radius: 5},
    connectorStyle: {
        outlineStroke: '#61B7CF',
        strokeWidth: 1,
        strokeStyle: "#61B7CF",
        fillStyle: "transparent",
        radius: 5,
        lineWidth: 2
    },
    connector: ["Flowchart", {stub: [40, 60], gap: 10, cornerRadius: 5, alwaysRespectStubs: true}],
    maxConnections: -1,
    connectorOverlays: [['Arrow', {width: 12, length: 12, location: 0.5}]]
}

//渲染
function lumbLoad(jspl, json, event) {
    lumb = jspl;
    instance = window.jsp = lumb.getInstance({
        DragOptions: {cursor: 'pointer', zIndex: 2000},
        Container: "canvas"
    });
    jsonp=json;
    eve=event;
    if (loadHTML(json, event)) {
        loadLINE(json);
    }
    instance.bind("connectionDragStop", function (connection) {
        //删除连线
        debugger;
        if(connection.connector==null){
            for(var j=0;j<jsonp['line'].length;j++){
                if(jsonp['line'][j]['begin']==connection.sourceId&&jsonp['line'][j]['end']==connection.targetId){
                    jsonp['line'].splice(j,1);
                }
            }
        }
        for (var key in connection._jsPlumb.overlays) {
            var id=connection._jsPlumb.overlays[key]['id']
            for(var j=0;j<jsonp['line'].length;j++){
                //修改连线
                if(jsonp['line'][j]['id']==id){
                    jsonp['line'][j]['begin']=connection.sourceId;
                    jsonp['line'][j]['end']=connection.targetId;
                    break;
                }
                //新增连线
                if(j==jsonp['line'].length-1&&jsonp['line'][j]['id']!=id){
                    var jxp=jsonp['line'];
                    var nx={
                        "begin":connection.sourceId,
                        "end":connection.targetId,
                        "id":""+getDete("r")
                    }
                    jxp.push(nx);
                    jsonp['line']=jxp;
                    break;
                }
            }
        }
        $(eve).html("");
        lumbLoad(lumb,jsonp,eve);
        return;
    });
    lumb.fire("jsPlumbDemoLoaded", instance);
}

//渲染节点
function loadHTML(json, event) {
    try {
        $(event).html("");
        instance.setContainer($(event).attr("id"));
        for (var i = 0; i < json['data'].length; i++) {
            //先在画布添加节点
            if(_addHTML(json['data'][i])){
                instance.draggable($("#"+json['data'][i]['id']+""),{
                    stop:function (e,ui) {
                        e=e.el;
                        var left=$(e).css("left");
                        var top=$(e).css("top");
                        var id=$(e).attr("id");
                        for(var i=0;i<jsonp['data'].length;i++){
                            if(jsonp['data'][i]['id']==id){
                                jsonp['data'][i]['top']=top;
                                jsonp['data'][i]['left']=left;
                                break;
                            }
                        }

                        var xpa=jsonp;
                    }
                });
                instance.addEndpoint(json['data'][i]['id'], common, {
                    anchors: ['Right']
                });
                instance.addEndpoint(json['data'][i]['id'], common, {
                    anchors: ['Top']
                })
                instance.addEndpoint(json['data'][i]['id'], common, {
                    anchors: ['Left']
                })
                instance.addEndpoint(json['data'][i]['id'], common, {
                    anchors: ['Bottom']
                })
            }
        }
        return true;
    } catch (e) {
        return false;
    }
}
//新增节点
function _addHTML(json) {
   try {
       var is=0;
       switch (json['type']) {
           case "101":
               $(eve).append("<div  onclick='level_nature(this)' id='" + json['id'] + "' class='palette level window jtk-node' style='left:" + json['left'] + ";top:" + json['top'] + "'><strong>" + json['name'] + "</strong><br/><br/></div>");
               is=1;
               break;
           case "104":
               $(eve).append("<div  onclick='level_nature(this)' id='" + json['id'] + "' class='palette level window begin-node' style='left:" + json['left'] + ";top:" + json['top'] + "'><strong>" + json['name'] + "</strong><br/><br/></div>");
               is=1;
               break;
           case "105":
               $(eve).append("<div  onclick='level_nature(this)' id='" + json['id'] + "' class='palette level window end-node' style='left:" + json['left'] + ";top:" + json['top'] + "'><strong>" + json['name'] + "</strong><br/><br/></div>");
               is=1;
               break;
           case "102":
               $(eve).append("<div  onclick='level_nature(this)' id='" + json['id'] + "' class='palette level window dr-node' style='left:" + json['left'] + ";top:" + json['top'] + "'><strong>" + json['name'] + "</strong><br/><br/></div>");
               is=1;
               break;
           case "103":
               $(eve).append("<div  onclick='level_nature(this)' id='" + json['id'] + "' class='palette level window hq-node' style='left:" + json['left'] + ";top:" + json['top'] + "'><strong>" + json['name'] + "</strong><br/><br/></div>");
               is=1;
               break;
       }
       if(is==0){
           return false;
       }else{
           return true;
       }
   }catch (e) {
       return false;
   }
}
//节点连线
function loadLINE(json) {
    for (var i = 0; i < json['line'].length; i++) {
        instance.connect({
            source: json['line'][i]['begin'],
            target: json['line'][i]['end'],
            paintStyle: {strokeWidth: 3, stroke: "#61B7CF"},
            endpointStyle: {fill: '#7AB02C', outlineStroke: 'darkgray', outlineWidth: 1, radius: 5},
            overlays: [['Arrow', {width: 12, length: 12, location: 0.5,id:json['line'][i]['id']}]],
            endpoint: 'Dot',
            connector: ['Flowchart'],
            anchor: ['Left', 'Right', 'Top', 'Bottom'],
            maxConnections: -1,
            isTarget: true,
            isSource: true
        })
    }
}

//删除节点
var _removeFK = function (id) {
    for(var i=0;i<jsonp['data'].length;i++){
        if(jsonp['data'][i]['id']==id){
            jsonp['data'].splice(i,1);
        }
    }
    for(var i=0;i<jsonp['line'].length;i++){
        if(jsonp['line'][i]['begin']==id||jsonp['line'][i]['end']==id){
            jsonp['line'].splice(i,1);
        }
    }
    instance.remove(id);
}
//增加节点
function _addFK(id,names,top,left,type) {
    var jp={
        "id":id,
        "name":names,
        "top":top,
        "left":left,
        "type":type
    };
    var jps=jsonp['data'];
    jps.push(jp);
    jsonp['data']=jps;
    $(eve).html("");

    lumbLoad(lumb,jsonp,eve);
}